const express = require('express');
const CryptoJs = require('crypto-js');
const UserModel = require('../models/user');
const customerInfoModel=require('../models/customerInfo');
const { Message,MessageList } = require('../utils/message');

const router = express.Router();

//获取用户列表
router.get('/:username?', (req, res, next) => {
  const {username} = req.params;
  if(username){//有动态路由参数时查询单个数据
    UserModel.findOne({username}).then(data => {
      if(data){
        const userData={...data._doc}
        delete userData.password
        res.json({
          code: 200,
          data: {
            status: 200,
            data: userData
          }
        })
      }else{
        res.json({
          code: 200,
          data: {
            status: 400,
            message: '未查找到数据！'
          }
        })
      }
    })
  }else{//没有动态路由参数时查询列表数据
    let {page=1,pageSize=10}=req.query
    page=Number(page)
    pageSize=Number(pageSize)
    UserModel.where('role').ne('normal').count((err,count)=>{
      UserModel.where('role').ne('normal')
        .limit(pageSize)
        .skip((page-1)*pageSize)
        .then(data=>{
          res.json({
            code: 200,
            data: {
              status: 200,
              list: data,
              page,
              pageSize,
              total: count
            }
          })
        })
    })
  }
});

//新增用户
router.post('/', (req, res, next) => {
  const { username, password, role} = req.body;
  if(username&&password&&role){//判断信息为不为空
    UserModel.find({ username }).then(data => {
      if (data.length > 0) {
        res.json({
          code: 200,
          data: {
            status: 400,
            message: '该用户已被注册！',
            userInfo: null
          }
        });
        return
      }
      // const passwordHash = CryptoJs.MD5(password);
      const user = new UserModel({ username, password: password, role });
      user.save().then(data => {
        const userMsg = { ...data._doc }
        delete userMsg.password
        res.json({
          code: 200,
          data: {
            status: 200,
            message: '注册成功',
            userMsg
          }
        });
        // const userInfo = new userInfoModel({userId: userMsg._id, username, nickname: '', sex: '', registDate: new Date(), userType: 0, role: 'normal'});
        // userInfo.save();
      });
  
    });
  }else{
    res.json({
      code: 200,
      data: {
        status: 400,
        message: '注册失败！',
        userInfo: null
      }
    });
  }
});

//删除用户
router.delete('/:username', (req, res, next) => {
  const { username } = req.params;
  const { option }=req.query;//option为删除用户的方式，0为管理员删除，1为用户自己注销
  const {password} = req.body;
  if(option==0){
    UserModel.deleteOne({ username }).then(data => {
      if (data.deletedCount !== 0) {
        res.json(Message(200,'删除成功！'))
        customerInfoModel.deleteOne({username}).then(data=>{
          if (data.deletedCount !== 0) {
            console.log('删除一条顾客信息！')
          }
        })
      } else {
        res.json(Message(400,'未删除任何数据'))
      }
    })
  }else{
    UserModel.find({username}).then(data => {
      if(data.length > 0){
        const userMsg = {...data[0]._doc};
        if(CryptoJs.MD5(password).toString() !== userMsg.password) {
          res.json(Message(400,'注销失败！密码错误。')) 
        } else {
          //删除用户及用户详细信息
          UserModel.deleteOne({username}).then(data => {
              if (data.deletedCount !== 0) {
                customerInfoModel.deleteOne({username})
                .then(data => {
                  if (data.deletedCount !== 0) {
                    res.json(Message(200,'注销成功！'))
                  }
                })
              } else {
                res.json(Message(400,'未删除任何数据'))
              }
          })
        }
      }
    })
  }
})

//修改用户
router.put('/',(req,res,next)=>{
  const {username,password,role}=req.body;
  UserModel.updateOne({username},{password,role}).then(data=>{
    if(data.modifiedCount !== 0){
      res.json({
        code: 200,
        data: {
          status: 200,
          message: '修改成功！'
        }
      })
    }else if(data.modifiedCount === 0&&data.matchedCount!==0){
      res.json({
        code: 200,
        data: {
          status: 400,
          message: '修改失败，未修改任何数据！'
        }
      })
    }else if(data.modifiedCount===0&&data.matchedCount===0){
      res.json({
        code: 200,
        data: {
          status: 400,
          message: '修改失败，没有该数据！'
        }
      })
    }
  })
})

module.exports = router